package com.LeeCode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 验证二叉搜索树
 */

public class Code098 {

    public List<Integer> list = new ArrayList<>();

    public static void main(String[] args) {

    }

    private Integer prev = null;

    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;
        boolean left = isValidBST(root.left);

        if (!left) return false;

        if (prev != null) {
            if (root.val <= prev) return false;
        }
        prev = root.val;
        return isValidBST(root.right);
    }


    public boolean isValidBST1(TreeNode root) {
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public boolean isValidBST(TreeNode node, long lower, long upper) {
        if (node == null) {
            return true;
        }
        if (node.val <= lower || node.val >= upper) {
            return false;
        }
        return isValidBST(node.left, lower, node.val) && isValidBST(node.right, node.val, upper);
    }

    public boolean isValidBST2(TreeNode root) {
        boolean flag = true;
        innerTravel(root);
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i) < list.get(i - 1)) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    public void innerTravel(TreeNode root) {
        if (root == null) {
            return;
        }
        innerTravel(root.left);
        list.add(root.val);
        innerTravel(root.right);
    }

    public boolean isValidBST3(TreeNode root) {
        TreeNode node = root, prev = null;

        Deque<TreeNode> stack = new LinkedList<>();
        while (node != null || !stack.isEmpty()) {
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
            node = stack.pop();
            if (prev != null) {
                if (node.val <= prev.val) {
                    return false;
                }
            }
            prev = node;
            node = node.right;
        }
        return true;
    }

}
